package org.hydrakyoufeng.vv.resource;

import com.qiniu.util.Auth;
import org.hydrakyoufeng.vv.Result;
import org.hydrakyoufeng.vv.configuration.TokenCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

@Controller
@RequestMapping("resource")
public class ResourceController {

    @Value("${myconfig.accessKey}")
    private String accessKey;

    @Value("${myconfig.secretKey}")
    private String secretKey;

    @Value("${myconfig.qiNiuRemoteAddr}")
    private String qiNiuRemoteAddr;

    @Value("${myconfig.bucket}")
    private String bucket;

    @Autowired
    private TokenCache tokenCache;

    @RequestMapping("getToken")
    @ResponseBody
    public Result getToken(@RequestHeader(value="Authorization",required=false)  String authorization) {
        if (null == authorization || tokenCache.get(authorization) == null) {
            return Result.fail("用户身份不合法");
        }
        Auth auth = Auth.create(accessKey, secretKey);
        String token = auth.uploadToken(bucket);
        var map = new HashMap<String, String>();
        map.put("token", token);
        map.put("remoteAddr", qiNiuRemoteAddr);
        return Result.ok(map);
    }

}
